/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.clarice.homechef.dao;

import com.clarice.homechef.domain.Bill;
import com.clarice.homechef.domain.Orders;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Akshay Velhal
 */
@Repository
public class BillDaoImpl implements BillDao{

    @Autowired
    DataSource dataSource;
    private static String sqlInsertBill = "insert into bill (userid, amount) values (?,?)";
    private static String sqlInsertOrders = "insert into orders (billid, mealid, chefid, quantity, price) values (?,?,?,?,?)";

    public int createNewBill(Bill bill) throws Exception {
        try (Connection conn = dataSource.getConnection();
                PreparedStatement psAddBill = conn.prepareStatement(sqlInsertBill, PreparedStatement.RETURN_GENERATED_KEYS);
                PreparedStatement psAddOrders = conn.prepareStatement(sqlInsertOrders);) {
            
            psAddBill.setInt(1, bill.getUserId());
            psAddBill.setDouble(2, bill.getAmount());
            psAddBill.executeUpdate();
            ResultSet rs = psAddBill.getGeneratedKeys();
            while(rs.next()) {
                bill.setBillId(rs.getInt("billid"));
            }
            /////////////////////////////////////////////////////////////////////////////////
            for(Orders order : bill.getOrders()) {
                psAddOrders.setInt(1, bill.getBillId());
                psAddOrders.setInt(2, order.getMealId());
                psAddOrders.setInt(3, order.getChefId());
                psAddOrders.setInt(4, order.getQuantity());
                psAddOrders.setDouble(5, order.getPrice());
                psAddOrders.addBatch();
            }
            psAddOrders.executeBatch();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return bill.getBillId();
    }
}
